package com.suray.wcs.service.thread;

import com.suray.basic.wcs.path.core.Node;
import com.suray.basic.wcs.utils.Coord;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.wcs.service.core.util.LockNodeManager;
import com.suray.wcs.service.pojo.Rgv;
import com.suray.wcs.service.system.service.impl.NodeDBServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class RgvReleaseLockThread {
    private static final NodeDBServiceImpl nodeDBService = SpringContextHolder.getBean(NodeDBServiceImpl.class);
    private static Logger log = LoggerFactory.getLogger(RgvReleaseLockThread.class);

    private Rgv rgv;

    public RgvReleaseLockThread(Rgv rgv) {
        this.rgv = rgv;
    }

    public void start() {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        Set<Coord> unlockSet = new HashSet<>();
        executorService.scheduleWithFixedDelay(() -> {
            Thread.currentThread().setName(rgv.getRgvName() + "资源释放线程");
            try {
                ArrayList<Node> waitReleaseNode = rgv.getWaitReleaseNode();
                int i1 = waitReleaseNode.indexOf(rgv.getCurLocation());
                if (i1 != -1) {
                    for (int i = 0; i < i1; i++) {
                        Node node = waitReleaseNode.get(0);
                        waitReleaseNode.remove(node);
                        Set<Coord> linkedNode = nodeDBService.getLinkedNode(node);
                        unlockSet.addAll(linkedNode);
                    }
                    Set<Coord> curLocationLinkedNode = nodeDBService.getLinkedNode(rgv.getCurLocation());
                    unlockSet.removeAll(curLocationLinkedNode);
                    LockNodeManager.removeLockedNodes(unlockSet, rgv);
                    unlockSet.clear();
                }
            } catch (Exception e) {
                log.error("{}释放锁定资源线程异常", rgv.getRgvName(), e);
            }
        }, 0, 800, TimeUnit.MILLISECONDS);
    }
}
